import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import os from 'os';

function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];
    if (iface) {
      for (const alias of iface) {
        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
          return alias.address;
        }
      }
    }
    return 'localhost'; // 默认回退到localhost
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
  ],
  preview: {
    host: '0.0.0.0',
    port: 5173,
    allowedHosts: ['personcom1236789.fucku.top'],
  },
  server: {
    host: '0.0.0.0',
    port: 5173,
    allowedHosts: ['personcom1236789.fucku.top'],
    proxy: {
      '/api': {
        target: `http://${getLocalIP()}:8080/`, // 使用环境变量作为API基础URL
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
})
